﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SeanLib.SeanCache
{
    /// <summary>
    /// 使用本类 需要单例模式
    /// </summary>
   public class CacheHelper:ICache
    {
        private Dictionary<string, CacheItem> _caches;
        public CacheHelper()
        {
            _caches = new Dictionary<string, CacheItem>();
        }

        #region [GetCache]

        /// <summary>
        /// 获取缓存
        /// </summary>
        public object GetCache(string key)
        {
            object obj = _caches.ContainsKey(key) ? _caches[key].Expired() ? null : _caches[key].Value : null;
            return obj;
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        public T GetCache<T>(string key)
        {
            object obj = GetCache(key);
            if (obj == null)
            {
                return default(T);
            }
            T result = (T)obj;
            return result;
        }
        #endregion

        #region [SetCache]
        /// <summary>
        /// 设置缓存
        /// </summary>
        public void SetCache(string key, object value, int expire = 300)
        {
            this._caches[key] = new CacheItem(key, value, expire);
        }
        #endregion

        #region [内部类]
        class CacheItem
        {
            #region 属性
            private object _value;
            public object Value
            {
                get { return _value; }
                set { _value = value; }
            }

            private string _key;
            public string Key
            {
                get { return _key; }
                set { _key = value; }
            }
            #endregion

            #region 内部变量
            /// <summary>  
            /// 插入时间  
            /// </summary>  
            private DateTime _insertTime;
            /// <summary>  
            /// 过期时间  
            /// </summary>  
            private int _expire;
            #endregion

            #region 构造函数
            /// <summary>  
            /// 构造函数  
            /// </summary>  
            /// <param name="key">缓存的KEY</param>  
            /// <param name="value">缓存的VALUE</param>  
            /// <param name="expire">缓存的过期时间</param>  
            public CacheItem(string key, object value, int expire)
            {
                this._key = key;
                this._value = value;
                this._expire = expire;
                this._insertTime = DateTime.Now;
            }
            #endregion

            #region Expired
            /// <summary>  
            /// 是否过期  
            /// </summary>  
            /// <returns></returns>  
            public bool Expired()
            {
                return DateTime.Now > this._insertTime.AddSeconds(_expire);
            }
            #endregion
        }
        #endregion
    }
}
